module.exports = (app) => {
  const express = require("express");
  const router = express.Router();
  const Article = require("../model/articleModel");

  // 添加文章
  router.post("/add", async (q, s) => {
    let res = await Article.create(q.body);
    s.send({
      success: "true",
      data: res,
    });
  });

  router.get("/delete/:id", async (q, s) => {
    let article = await Article.findOne({ _id: q.params.id });
    if (article != null) {
      await article.remove();
      s.send({
        data: "",
        success: "true",
      });
    } else {
      s.send({
        data: "找不到此文章!",
        success: "false",
      });
    }
  });

  router.get("/getAllArticle", async (q, s) => {
    let article = await Article.find();
    s.send(article);
  });

  router.get("/getOneArticle/:id", async (q, s) => {
    let article = await Article.findOne({ _id: q.params.id });
    s.send(article);
  });

  // 查找物品（模糊查询）
  router.get("/find/:title", async (q, s) => {
    let reg = new RegExp(q.params.title, "g");
    let article = await Article.find({
      $or: [{ title: { $regex: reg } }],
    });
    s.send(article);
  });

  // 修改物品信息
  router.post("/update/:id", async (q, s) => {
    let article = await Article.findOne({ _id: q.params.id });
    if (article != null) {
      article.type = q.body.type == undefined ? article.type : q.body.type;
      article.title = q.body.title == undefined ? article.title : q.body.title;
      article.subtitle =
        q.body.subtitle == undefined ? article.subtitle : q.body.subtitle;
      article.content =
        q.body.content == undefined ? article.content : q.body.content;
      article.head_img =
        q.body.head_img == undefined ? article.head_img : q.body.head_img;
      article.time = q.body.time == undefined ? article.time : q.body.time;
      article.author =
        q.body.author == undefined ? article.author : q.body.author;
      await article.save();
      s.send({
        data: article,
        success: "true",
      });
    } else {
      s.send({
        data: "找不到此文章!",
        success: "false",
      });
    }
  });

  // 批量修改
  router.post("/batchUpdate", async (q, s) => {
    let article = await Article.find();
    article = JSON.parse(JSON.stringify(q.body.article));
    Article.updateMany();
    s.send(article);
  });

  app.use("/article", router);
};
